// @ts-ignore
import request from 'axios'
// 删除隐患的API接口
export function deleteDangerById(hazardId: number | string) {
  return request({
    url: '/inspection/hazard/deletebyid',
    method: 'get',
    params: { hazardId }
  })
}

export function getDangerList(params: any) {
  // 转换前端参数名称为后端参数名称
  const apiParams: Record<string, any> = {
    pageNum: params.current || 1,
    pageSize: params.size || 10,
    hazardLevel: params.level || undefined,
    hazardSource: params.source || undefined,
    hazardType: params.type || undefined,
    securityId: params.securityId || undefined,
    startReportTime: params.startDate ? formatDateToDateTime(params.startDate) : undefined,
    endReportTime: params.endDate ? formatDateToDateTime(params.endDate, true) : undefined,
    startEndTime: params.startEndDate ? formatDateToDateTime(params.startEndDate) : undefined,
    endEndTime: params.endEndDate ? formatDateToDateTime(params.endEndDate, true) : undefined,
    status: params.status !== undefined && params.status !== '' ? params.status : undefined,
    handler: params.reporter || undefined
  }

  // 移除所有undefined的参数，避免传递无效参数
  Object.keys(apiParams).forEach(key => {
    if (apiParams[key] === undefined) {
      delete apiParams[key]
    }
  })

  console.log('发送请求参数:', apiParams)

  // 确保使用正确的API地址
  return request({
    url: '/inspection/hazard/list', // 使用相对路径，让Vite的代理处理
    method: 'get',
    params: apiParams
  })
}

// 日期格式化辅助函数
function formatDateToDateTime(date: Date | string, isEndOfDay = false): string {
  if (!date) return '';

  const d = new Date(date);

  // 如果是当天结束时间，设置为23:59:59
  if (isEndOfDay) {
    d.setHours(23, 59, 59, 999);
  } else {
    d.setHours(0, 0, 0, 0);
  }

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 审核隐患
export const auditDanger = (data: any) => {
  return request({
    url: '/inspection/hazard/audit',
    method: 'post',
    data
  })
}
